# Canny 边缘检测实战 引入霍夫变换 同时引入RIO

# 导入所需包
import matplotlib.pyplot as plt
import matplotlib.image as mping
import cv2
import numpy as np
# 传入图片
img = mping.imread('test4.jpg')
plt.imshow(img)
plt.show()
# 输出图片格式与大小
print('This image is: ', type(img), 'with dimensions: ', img.shape)


# imshape = [img.shape[0], img.shape[1]]
# img = np.copy(img)
# img = np.array([[(0,imshape[0]),(450, 290), (490, 290), (imshape[1],imshape[0])]], dtype=np.int32)

# 将图片转化为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

# 定义高斯平滑/模糊的内核大小
# 再cv2.Canny()内部已经应用了 5*5 的高斯平滑/模糊
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)

# 定义Canny算子的参数
# 推荐的高低比为 1：2 或 1：3
low_threshold = 50
high_threshold = 150
edges = cv2.Canny(blur_gray, low_threshold, high_threshold)

# 使用cv2.fillPoly()定义图象
mask = np.zeros_like(edges)   
ignore_mask_color = 255 

# 定义一个兴趣区域
imshape = img.shape
print(imshape[0], imshape[1])
vertices = np.array([[(0,imshape[0]),(450, 290), (490, 290), 
                      (imshape[1],imshape[0])]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)

# 定义霍夫变换参数
# 制作一个与要绘制的图像大小相同的空白
rho = 2
theta = np.pi / 180
threshold = 15
min_line_length = 100
max_line_gap = 20

# 创建一个绘制线条的空白
line_image = np.copy(img) * 0

# 在边缘检测到的图像上运行 Hough
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),
                            min_line_length, max_line_gap)

# 遍历所有线 并且在空白上填充颜色
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)

# 创建一个带有色彩的二值图像 与 线图象结合
color_edges = np.dstack((masked_edges, masked_edges, masked_edges)) 

# 绘制线条
combo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) 
plt.imshow(combo)
plt.show()
